<template>
  <div class="coupon-detail">
    <!-- 基本信息卡片 -->
    <el-card class="info-card">
      <template #header>
        <div class="card-header">
          <span>优惠券基本信息</span>
          <el-button-group>
            <el-button type="primary" @click="handleEdit">编辑</el-button>
            <el-button type="danger" @click="handleDelete" :disabled="coupon.status === 'running'">
              删除
            </el-button>
          </el-button-group>
        </div>
      </template>
      <el-descriptions :column="3" border>
        <el-descriptions-item label="优惠券名称">{{ coupon.name }}</el-descriptions-item>
        <el-descriptions-item label="优惠券类型">
          <el-tag :type="getCouponTypeTag(coupon.type)">
            {{ getCouponTypeName(coupon.type) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="优惠券状态">
          <el-tag :type="getCouponStatusTag(coupon.status)">
            {{ getCouponStatusName(coupon.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="优惠金额">
          <template v-if="coupon.type === 'discount'">
            {{ coupon.discount }}折
          </template>
          <template v-else>
            ¥{{ coupon.amount }}
          </template>
        </el-descriptions-item>
        <el-descriptions-item label="使用门槛">
          <template v-if="coupon.minAmount > 0">
            满{{ coupon.minAmount }}元可用
          </template>
          <template v-else>
            无门槛
          </template>
        </el-descriptions-item>
        <el-descriptions-item label="有效期">
          {{ coupon.startTime }} 至 {{ coupon.endTime }}
        </el-descriptions-item>
        <el-descriptions-item label="发放总量">{{ coupon.totalQuantity }}</el-descriptions-item>
        <el-descriptions-item label="已发放">{{ coupon.issuedQuantity }}</el-descriptions-item>
        <el-descriptions-item label="已使用">{{ coupon.usedQuantity }}</el-descriptions-item>
        <el-descriptions-item label="使用说明" :span="3">{{ coupon.description }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 数据统计卡片 -->
    <el-row :gutter="20" class="statistics-cards">
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>领取人数</span>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">{{ statistics.receiveCount }}</div>
            <div class="trend">
              较昨日
              <span :class="statistics.receiveTrend >= 0 ? 'up' : 'down'">
                {{ Math.abs(statistics.receiveTrend) }}%
                <el-icon>
                  <component :is="statistics.receiveTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>使用人数</span>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">{{ statistics.useCount }}</div>
            <div class="trend">
              较昨日
              <span :class="statistics.useTrend >= 0 ? 'up' : 'down'">
                {{ Math.abs(statistics.useTrend) }}%
                <el-icon>
                  <component :is="statistics.useTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>使用率</span>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">{{ statistics.useRate }}%</div>
            <div class="trend">
              较昨日
              <span :class="statistics.useRateTrend >= 0 ? 'up' : 'down'">
                {{ Math.abs(statistics.useRateTrend) }}%
                <el-icon>
                  <component :is="statistics.useRateTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>带动销售额</span>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">¥{{ statistics.sales }}</div>
            <div class="trend">
              较昨日
              <span :class="statistics.salesTrend >= 0 ? 'up' : 'down'">
                {{ Math.abs(statistics.salesTrend) }}%
                <el-icon>
                  <component :is="statistics.salesTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据趋势图表 -->
    <el-card class="chart-card">
      <template #header>
        <div class="card-header">
          <span>数据趋势</span>
          <el-radio-group v-model="chartType" size="small">
            <el-radio-button label="receive">领取人数</el-radio-button>
            <el-radio-button label="use">使用人数</el-radio-button>
            <el-radio-button label="rate">使用率</el-radio-button>
            <el-radio-button label="sales">销售额</el-radio-button>
          </el-radio-group>
        </div>
      </template>
      <div class="chart-container">
        <v-chart :option="chartOption" autoresize />
      </div>
    </el-card>

    <!-- 发放记录列表 -->
    <el-card class="record-card">
      <template #header>
        <div class="card-header">
          <span>发放记录</span>
          <div class="header-operations">
            <el-button type="primary" @click="handleBatchIssue">批量发放</el-button>
            <el-button type="success" @click="handleExport">导出记录</el-button>
          </div>
        </div>
      </template>
      <el-table :data="recordList" border style="width: 100%">
        <el-table-column prop="memberName" label="会员名称" min-width="120" />
        <el-table-column prop="memberLevel" label="会员等级" width="120">
          <template #default="{ row }">
            <el-tag>{{ row.memberLevel }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="receiveTime" label="领取时间" width="180" />
        <el-table-column prop="useTime" label="使用时间" width="180">
          <template #default="{ row }">
            {{ row.useTime || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="orderAmount" label="订单金额" width="120">
          <template #default="{ row }">
            {{ row.orderAmount ? `¥${row.orderAmount}` : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getCouponRecordStatusTag(row.status)">
              {{ getCouponRecordStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="row.status === 'used'"
              type="primary"
              link
              @click="handleViewOrder(row)"
            >
              查看订单
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="recordPage.current"
          v-model:page-size="recordPage.size"
          :total="recordPage.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleRecordSizeChange"
          @current-change="handleRecordCurrentChange"
        />
      </div>
    </el-card>

    <!-- 批量发放对话框 -->
    <el-dialog
      v-model="batchIssueDialog.visible"
      title="批量发放优惠券"
      width="500px"
    >
      <el-form
        ref="batchIssueFormRef"
        :model="batchIssueDialog.form"
        :rules="batchIssueDialog.rules"
        label-width="100px"
      >
        <el-form-item label="发放方式" prop="type">
          <el-radio-group v-model="batchIssueDialog.form.type">
            <el-radio label="level">会员等级</el-radio>
            <el-radio label="tag">会员标签</el-radio>
            <el-radio label="custom">指定会员</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          v-if="batchIssueDialog.form.type === 'level'"
          label="会员等级"
          prop="levelIds"
        >
          <el-select
            v-model="batchIssueDialog.form.levelIds"
            multiple
            placeholder="请选择会员等级"
          >
            <el-option
              v-for="level in memberLevels"
              :key="level.id"
              :label="level.name"
              :value="level.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          v-if="batchIssueDialog.form.type === 'tag'"
          label="会员标签"
          prop="tagIds"
        >
          <el-select
            v-model="batchIssueDialog.form.tagIds"
            multiple
            placeholder="请选择会员标签"
          >
            <el-option
              v-for="tag in memberTags"
              :key="tag.id"
              :label="tag.name"
              :value="tag.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          v-if="batchIssueDialog.form.type === 'custom'"
          label="指定会员"
          prop="memberIds"
        >
          <el-select
            v-model="batchIssueDialog.form.memberIds"
            multiple
            filterable
            remote
            :remote-method="handleSearchMembers"
            placeholder="请输入会员名称搜索"
          >
            <el-option
              v-for="member in memberOptions"
              :key="member.id"
              :label="member.name"
              :value="member.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="发放数量" prop="quantity">
          <el-input-number
            v-model="batchIssueDialog.form.quantity"
            :min="1"
            :max="coupon.remainingQuantity"
          />
          <span class="form-tip">
            剩余可发放数量：{{ coupon.remainingQuantity }}
          </span>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="batchIssueDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleBatchIssueSubmit">
          确认发放
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart } from 'echarts/charts'
import { GridComponent, TooltipComponent, LegendComponent } from 'echarts/components'
import VChart from 'vue-echarts'
import {
  getMerchantCouponDetail,
  deleteMerchantCoupon,
  getMerchantCouponStatistics,
  getMerchantCouponTrend,
  getMerchantCouponRecords,
  exportMerchantCouponData,
  batchIssueMerchantCoupon,
  getMerchantMemberLevels,
  getMerchantMemberTags,
  searchMerchantMembers
} from '@/api/merchant'

// 注册 ECharts 组件
use([CanvasRenderer, LineChart, GridComponent, TooltipComponent, LegendComponent])

const route = useRoute()
const router = useRouter()
const couponId = route.params.id

// 优惠券信息
const coupon = ref({})

// 统计数据
const statistics = reactive({
  receiveCount: 0,
  receiveTrend: 0,
  useCount: 0,
  useTrend: 0,
  useRate: 0,
  useRateTrend: 0,
  sales: 0,
  salesTrend: 0
})

// 图表数据
const chartType = ref('receive')
const chartData = ref({
  dates: [],
  receive: [],
  use: [],
  rate: [],
  sales: []
})

// 发放记录
const recordList = ref([])
const recordPage = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 批量发放对话框
const batchIssueDialog = reactive({
  visible: false,
  form: {
    type: 'level',
    levelIds: [],
    tagIds: [],
    memberIds: [],
    quantity: 1
  },
  rules: {
    type: [{ required: true, message: '请选择发放方式', trigger: 'change' }],
    levelIds: [{ required: true, message: '请选择会员等级', trigger: 'change' }],
    tagIds: [{ required: true, message: '请选择会员标签', trigger: 'change' }],
    memberIds: [{ required: true, message: '请选择会员', trigger: 'change' }],
    quantity: [{ required: true, message: '请输入发放数量', trigger: 'blur' }]
  }
})

// 会员等级和标签
const memberLevels = ref([])
const memberTags = ref([])
const memberOptions = ref([])

// 获取优惠券详情
const getCouponDetail = async () => {
  try {
    const { data } = await getMerchantCouponDetail(couponId)
    coupon.value = data
  } catch (error) {
    console.error('获取优惠券详情失败:', error)
    ElMessage.error('获取优惠券详情失败')
  }
}

// 获取统计数据
const getStatistics = async () => {
  try {
    const { data } = await getMerchantCouponStatistics(couponId)
    Object.assign(statistics, data)
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败')
  }
}

// 获取趋势数据
const getTrendData = async () => {
  try {
    const { data } = await getMerchantCouponTrend(couponId)
    chartData.value = data
  } catch (error) {
    console.error('获取趋势数据失败:', error)
    ElMessage.error('获取趋势数据失败')
  }
}

// 获取发放记录
const getRecordList = async () => {
  try {
    const params = {
      page: recordPage.current,
      size: recordPage.size
    }
    const { data } = await getMerchantCouponRecords(couponId, params)
    recordList.value = data.list
    recordPage.total = data.total
  } catch (error) {
    console.error('获取发放记录失败:', error)
    ElMessage.error('获取发放记录失败')
  }
}

// 获取会员等级
const getMemberLevels = async () => {
  try {
    const { data } = await getMerchantMemberLevels()
    memberLevels.value = data
  } catch (error) {
    console.error('获取会员等级失败:', error)
    ElMessage.error('获取会员等级失败')
  }
}

// 获取会员标签
const getMemberTags = async () => {
  try {
    const { data } = await getMerchantMemberTags()
    memberTags.value = data
  } catch (error) {
    console.error('获取会员标签失败:', error)
    ElMessage.error('获取会员标签失败')
  }
}

// 搜索会员
const handleSearchMembers = async (query) => {
  if (query) {
    try {
      const { data } = await searchMerchantMembers({ keyword: query })
      memberOptions.value = data
    } catch (error) {
      console.error('搜索会员失败:', error)
    }
  } else {
    memberOptions.value = []
  }
}

// 图表配置
const chartOption = computed(() => ({
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: [getChartTitle(chartType.value)]
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: chartData.value.dates
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: getChartTitle(chartType.value),
      type: 'line',
      smooth: true,
      data: chartData.value[chartType.value]
    }
  ]
}))

// 获取图表标题
const getChartTitle = (type) => {
  const map = {
    receive: '领取人数',
    use: '使用人数',
    rate: '使用率',
    sales: '销售额'
  }
  return map[type] || ''
}

// 优惠券类型标签
const getCouponTypeTag = (type) => {
  const map = {
    discount: 'success',
    amount: 'warning'
  }
  return map[type] || ''
}

// 优惠券类型名称
const getCouponTypeName = (type) => {
  const map = {
    discount: '折扣券',
    amount: '满减券'
  }
  return map[type] || type
}

// 优惠券状态标签
const getCouponStatusTag = (status) => {
  const map = {
    draft: 'info',
    pending: 'warning',
    running: 'success',
    ended: ''
  }
  return map[status] || ''
}

// 优惠券状态名称
const getCouponStatusName = (status) => {
  const map = {
    draft: '草稿',
    pending: '待开始',
    running: '进行中',
    ended: '已结束'
  }
  return map[status] || status
}

// 优惠券记录状态标签
const getCouponRecordStatusTag = (status) => {
  const map = {
    unused: 'warning',
    used: 'success',
    expired: 'info'
  }
  return map[status] || ''
}

// 优惠券记录状态名称
const getCouponRecordStatusName = (status) => {
  const map = {
    unused: '未使用',
    used: '已使用',
    expired: '已过期'
  }
  return map[status] || status
}

// 编辑优惠券
const handleEdit = () => {
  router.push(`/merchant/marketing/coupon-edit/${couponId}`)
}

// 删除优惠券
const handleDelete = async () => {
  if (coupon.value.status === 'running') {
    ElMessage.warning('进行中的优惠券无法删除')
    return
  }
  try {
    await ElMessageBox.confirm('确认删除该优惠券吗？', '提示', {
      type: 'warning'
    })
    await deleteMerchantCoupon(couponId)
    ElMessage.success('删除成功')
    router.push('/merchant/marketing/coupon')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除优惠券失败:', error)
    }
  }
}

// 查看订单
const handleViewOrder = (row) => {
  router.push(`/merchant/order/detail/${row.orderId}`)
}

// 导出记录
const handleExport = async () => {
  try {
    const params = {
      couponId,
      type: 'record'
    }
    await exportMerchantCouponData(params)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出记录失败:', error)
    ElMessage.error('导出记录失败')
  }
}

// 批量发放
const handleBatchIssue = () => {
  batchIssueDialog.visible = true
  batchIssueDialog.form = {
    type: 'level',
    levelIds: [],
    tagIds: [],
    memberIds: [],
    quantity: 1
  }
}

// 提交批量发放
const handleBatchIssueSubmit = async () => {
  try {
    const params = {
      couponId,
      ...batchIssueDialog.form
    }
    await batchIssueMerchantCoupon(params)
    ElMessage.success('发放成功')
    batchIssueDialog.visible = false
    getCouponDetail()
    getRecordList()
  } catch (error) {
    console.error('批量发放失败:', error)
    ElMessage.error('批量发放失败')
  }
}

// 分页
const handleRecordSizeChange = (val) => {
  recordPage.size = val
  getRecordList()
}

const handleRecordCurrentChange = (val) => {
  recordPage.current = val
  getRecordList()
}

onMounted(() => {
  getCouponDetail()
  getStatistics()
  getTrendData()
  getRecordList()
  getMemberLevels()
  getMemberTags()
})
</script>

<style lang="scss" scoped>
.coupon-detail {
  padding: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .header-operations {
      display: flex;
      gap: 10px;
    }
  }

  .info-card {
    margin-bottom: 20px;
  }

  .statistics-cards {
    margin-bottom: 20px;

    .card-content {
      text-align: center;

      .amount {
        font-size: 24px;
        font-weight: bold;
        margin-bottom: 10px;
      }

      .trend {
        font-size: 14px;
        color: var(--el-text-color-secondary);

        .up {
          color: var(--el-color-success);
        }

        .down {
          color: var(--el-color-danger);
        }
      }
    }
  }

  .chart-card {
    margin-bottom: 20px;

    .chart-container {
      height: 400px;
    }
  }

  .record-card {
    margin-bottom: 20px;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .form-tip {
    margin-left: 10px;
    font-size: 14px;
    color: var(--el-text-color-secondary);
  }
}
</style> 